package com.withoutwords.engine;

import java.util.HashMap;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class BitmapCache {

	static BitmapCache _cacheInstance;

	private BitmapCache() {

		cache = new HashMap<Integer, BitmapDrawable>();
	}

	public static BitmapCache getCacheInstance() {
		if (_cacheInstance == null) {
			_cacheInstance = new BitmapCache();
		}
		return _cacheInstance;
	}

	/*Context context;

	public void setContext(Context context) {
		this.context = context;
	}*/

	HashMap<Integer, BitmapDrawable> cache;

	public synchronized Drawable getDrawable(Context context,int resId) {

		//System.gc();
		//Runtime.getRuntime().gc();
		BitmapDrawable dr = null;
		//synchronized (cache)
		{

			Integer res = new Integer(resId);
			dr = cache.get(res);
			if (dr == null) {
				try {
					Resources resources = context.getResources();
					dr = new BitmapDrawable(resources,
							BitmapFactory.decodeResource(
									resources, resId));
					if (!dr.getBitmap().isRecycled()) {
						cache.put(res, dr);
						//Log.e("getDrawable put in cache", "res = " + resId);
					} else {
						Log.e("getDrawable Bitmap is recycled", "res = "
								+ resId);
						dr = null;
					}
				} catch (Throwable e) {
					if(e != null && e.getMessage() != null)
					Log.e("exception loading",e.getMessage());
					System.gc();
					Runtime.getRuntime().gc();
					// TODO: handle exception
				}
			}

		}

		return dr;
	}

	public synchronized void deleteDrawable(int resId) {

		/*
		 * BitmapDrawable dr = null; dr = cache.get(new Integer(resId)); if (dr
		 * != null) { /*if(dr.getBitmap().) dr.getBitmap().recycle();
		 */
		BitmapDrawable dr = null;
		Integer res = new Integer(resId);
		dr = cache.get(res);
		if (dr != null) {

			
			synchronized (dr.getBitmap()) {
				dr.getBitmap().recycle();
				Log.e("deleteDrawable recycled", "res = " + resId);
				
			}
			synchronized (cache) {
				cache.remove(res);
				
			}	
		System.gc();
			Runtime.getRuntime().gc();
			
			

		}
		// }
		/*
		 * BitmapDrawable dr = null; dr = cache.get(new Integer(resId)); if (dr
		 * != null) { cac }
		 */
	}

}
